package handler

import (
	"encoding/json"
	"net/http"

	"gitee.com/kobeyyf/apibox/render"
)

const (
	STATUS_OK = "ok"
)

type Response struct {
	HttpCode int `json:"-" xml:"-" yaml:"-"`
	Action   string
	Code     string
	Data     interface{} `json:",omitempty" xml:",omitempty" yaml:",omitempty"`
	Message  string      `json:",omitempty" xml:",omitempty" yaml:",omitempty"`
}

func (c *Context) DebugWriteResponse() {

}

func (c *Context) WriteResponse(resp *Response) {
	if resp == nil {
		c.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*")
		return
	}
	if RewriteHttpCode {
		resp.HttpCode = 200
	}

	// logger.Infoln(resp.Action, resp.Code, resp.Message)

	format := c.Request.FormValue("Format")
	var r render.Render
	switch format {
	case "json":
		r = render.JSON{Data: resp}
	case "yaml":
		r = render.YAML{Data: resp}
	case "MsgPack":
		r = render.MsgPack{Data: resp}
	case "jsonp":
		callback := c.Request.FormValue("callback")
		if callback == "" {
			callback = "callback"
		}
		r = render.JsonpJSON{Callback: callback, Data: resp}
	case "xml":
		r = render.XML{Data: resp}
	case "ProtoBuf":
		r = render.ProtoBuf{Data: resp}
	default:
		r = render.JSON{Data: resp}
	}

	c.ResponseWriter.Header().Add("Access-Control-Allow-Origin", "*")
	c.ResponseWriter.WriteHeader(resp.HttpCode)
	r.Render(c.ResponseWriter)
}

func (resp *Response) ToJSON() []byte {
	buf, _ := json.Marshal(resp)
	return buf

}

func (c *Context) WriteErrorResponse(HttpCode int, code, message string) {
	c.WriteResponse(&Response{HttpCode: HttpCode, Code: code, Message: message})
}

func (c *Context) WriteSuccessResponse(data interface{}) {
	c.WriteResponse(&Response{HttpCode: http.StatusOK, Code: STATUS_OK, Data: data})
}

func NewErrorResponseWith400(code, message string) *Response {
	return &Response{Code: code, HttpCode: 400, Message: message}
}
func NewErrorResponseWith200(code, message string) *Response {
	return &Response{Code: code, HttpCode: 200, Message: message}
}

func NewSuccessResponse(data interface{}) *Response {
	return &Response{HttpCode: http.StatusOK, Code: STATUS_OK, Data: data}
}
